import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.imgscalr.Scalr.Mode;


public class DragPanel extends JPanel {

	private static final long serialVersionUID = -7875396161117147324L;
	private static BufferedImage[] sword = new BufferedImage[6];
	private int n = 0;
    private int w = 640;
    private int h = 640;
    private Point mousePt = new Point(w / 2, h / 2);
    private boolean clicked = false;
    
    public DragPanel(Dimension size, final MonsterGame game) {
    	this.w = size.width;
    	this.h = size.height;
    	this.setOpaque(false);
    	this.setBounds(0, 0, w, h);
        this.addMouseListener(new MouseAdapter() {
        	
        	@Override
        	public void mousePressed(MouseEvent e) {
        		if(!clicked){
	        		clicked = true;
	        		game.clicked(e.getPoint());
	        		new Thread(){
	        			@Override
	        			public void run() {
	        				for(int i = 1; i<6; i++){
	        					n = i;
	        					repaint();
	        					try {
									Thread.sleep(120);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
	        				}
	        				n = 0;
	        				repaint();
	        				clicked = false;
	        			}
	        		}.start();
        		}
        	}
        	@Override
        	public void mouseEntered(MouseEvent me) {
        		if(!clicked){
	                 mousePt = me.getPoint();
	                 repaint();
       		}
        	}
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
        	@Override
        	public void mouseMoved(MouseEvent me) {
        		if(!clicked){
	                 mousePt = me.getPoint();
	                 repaint();
        		}
        	}
        });
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(w, h);
    }
    
    @Override
    public void setPreferredSize(Dimension d) {
    	super.setPreferredSize(d);
    	this.w = d.width;
    	this.h = d.height;
    	this.setBounds(0, 0, w, h);
    	this.revalidate();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(sword[n] == null){
        	try {
    			sword[n] = ImageIO.read(new File("spada/spada runica"+(n+1)+".png"));
    			sword[n] = Scalr.resize(sword[n], Mode.FIT_TO_WIDTH, 400);
    		} catch (IOException e1) {
    			e1.printStackTrace();
    		}
        }
        g.drawImage(sword[n], mousePt.x - 133, mousePt.y - 297, null);
    }
}
